package com.wgn.reportquery.service;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wgn.reportquery.cons.Const;
import com.wgn.reportquery.dao.QueryDaoImple;
import com.wgn.reportquery.http.QueryHttpClient;
import com.wgn.reportquery.model.InputObj;
import com.wgn.reportquery.model.Query;
import com.wgn.reportquery.model.ReportDate;
import com.wgn.reportquery.model.Reportdata;
import com.wgn.reportquery.model.User_SK;
import com.wgn.reportquery.module.ChartReport;
import com.wgn.reportquery.rj.model.PhUserCard;
import com.wgn.reportquery.rj.model.RJUser;
import com.wgn.reportquery.thread.ImportSkThread;
import com.wgn.reportquery.utils.ReportUtils;

public class QueryService {
	QueryDaoImple dao;
	static String splitString0 = "～";
	static String splitString1 = "-";
	static String splitString2 = "--";
	String username;
	String dataType;

	public QueryService(String userName) {
		dao = new QueryDaoImple();
		username = userName;
	};

	public List<String> getCards() {

		return dao.getCards(username, "sk");
	}

	public String getDataType() {

		return "'" + dataType + "'";
	}

	List<String> xlist;
	List<String> ylist;
	List<String> biglist;
	List<String> smalllist;

	public String getBigList() {

		return ReportUtils.listToArray(biglist);

	}

	public String getSmallList() {
		return ReportUtils.listToArray(smalllist);
	}

	public String getxList() {
		return ReportUtils.listToArray(xlist);
	}

	public String getyList() {
		return ReportUtils.listToArray(ylist);
	}

	List<String> typelist;

	public String getAllDataTypeHtml() {

		typelist = dao.getAllDataType(username);
		return ReportUtils.getHtml(typelist);
	}

	public String getAllDataTypeHtmlTable() {
		if (tmpUsername.equals(username))
			return "";
		if (null == typelist)
			typelist = dao.getAllDataType(username);
		return ReportUtils.getHtmlTable(typelist);
	}

	List<Reportdata> reportdatas;
	static String tmpUsername = "tmp";

	public void getDataArray(String typeName) {

		dataType = typeName;
		int index = 0;
		xlist = new ArrayList();
		ylist = new ArrayList();
		smalllist = new ArrayList();
		biglist = new ArrayList();
		// list.add("90");
		// list.add("90");
		// list.add("80");
		// list.add("90");
		// list.add("70");
		// list.add("90");
		String dateLabel = "SELECT * FROM DATAS a WHERE info ='" + typeName
				+ "' and USERNAME='" + username + "' ORDER  BY a.`REPORTDATE`";
		reportdatas = dao.getAll(dateLabel);
		String small = "0";
		String big = "0";
		for (Reportdata datas : reportdatas) {
			xlist.add(datas.getReportdate());
			ylist.add(datas.getVal());
			if (0 == index++)// 赋予上下范围
			{

				String scope = datas.getScope().trim();
				String splitString = null;
				if (scope.indexOf(splitString0) != -1)
					splitString = splitString0;
				else if (scope.indexOf(splitString2) != -1)
					splitString = splitString2;
				else if (scope.indexOf(splitString1) != -1)
					splitString = splitString1;

				if (null != splitString) {
					try {
						String[] tmpArray = scope.split(splitString);
						small = tmpArray[0];
						big = tmpArray[tmpArray.length - 1];
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {// 无分隔符
					small = scope;
					big = scope;
				}

			}
			smalllist.add(small);
			biglist.add(big);
		}

	}

	public String look4type(String querytypevalue, String passwd)
			throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		List<String> list = dao.look4Type(username, querytypevalue);
		StringBuffer sf = new StringBuffer();
		for (String s : list) {
			// window.location.href="<%=basePath%>dosomequery?querytype=chart&datatype="+encodeURI(datatype);
			sf.append("<li><a href='dosomequery?querytype=chart&querytypevalue="
					+ java.net.URLEncoder.encode(s, "UTF-8")
					+ "'>"
					+ s
					+ "</a></li>");
		}
		if (null == list || list.size() == 0) {
			sf.append("<p>没找到项目</p>");
		}
		return sf.toString();
	}

	public String getHostpitalHtml() {
		List<String> list = dao.getHostPital();
		StringBuffer sb = new StringBuffer();
		int count = 0;
		int rowNum = 0;
		int maxColNum = 3;
		for (String str : list) {
			if (0 == count) {
				sb.append("<tr>");
			} else {
				if (count % maxColNum == 0) {
					++rowNum;
					sb.append(str).append("</tr>");
				} else if (count % maxColNum == 1) {
					sb.append("<tr>").append(str);
				} else {
					sb.append(str);
				}
			}
			++count;
		}
		if (sb.length() > 0)
			if (rowNum == 0 || count % maxColNum != 0)
				sb.append("</tr>");
		return sb.toString();
	}

	public boolean checkIfBindCards() {
		// TODO Auto-generated method stub
		return dao.checkIfBindCards(username);
	}

	public boolean checkIfBindRjCards() {
		// TODO Auto-generated method stub
		return dao.checkIfBindRjCards(username);
	}

	public boolean checkIfBindSkCards() {
		// TODO Auto-generated method stub
		return dao.checkIfBindSkCards(username);
	}

	public List<String> getRjCards() {
		// TODO Auto-generated method stub
		return dao.getCards(username, "rj");
	}

	public String bindrj(String rJUSERNAME, String passwd) {
		// TODO Auto-generated method stub
		// 登陆仁济app
		// 1.获得md5密码
		List<String> para = new ArrayList<String>();
		para.add(passwd);
		String passwd_md5 = dao.getString("SELECT MD5(?)", para);
		try {
			// 获得卡号
			QueryHttpClient q = new QueryHttpClient(rJUSERNAME, passwd_md5,
					"6", username);
			// 成功
			return "ok";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// 失败
			e.printStackTrace();
			return e.getMessage();
		}

	}

	public String getZbHtml() {
		/*
		 * <th>指标日期</th> <th>指标日期</th> <th>指标名称</th> <th>指标结果</th> <th>参考值</th>
		 * <th>比较结果</th> <th>单位</th>
		 */
		StringBuffer s = new StringBuffer();
		if (null != reportdatas) {
			for (Reportdata r : reportdatas) {
				String jg = r.getJg();
				try {
					if (null == jg) {
						float small = Float.parseFloat(this.smalllist.get(0)
								+ "f");
						float bigger = Float.parseFloat(this.biglist.get(0)
								+ "f");
						float val = Float.parseFloat(r.getVal() + "f");
						String i = "1";// 正常
						if (small == bigger) {
							jg = "";
						} else {
							if (val < small) {
								i = "2";
							} else if (val > bigger) {
								i = "3";
							}
							jg = ReportUtils.getVs(i);
						}
					} else {
						jg = ReportUtils.getVs(jg);
					}
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
					jg = "";
				}

				s.append("<tr><td>").append(r.getReportdate())
						.append("</td><td>").append(r.getInfo())
						.append("</td><td>").append(r.getVal())
						.append("</td><td>").append(r.getScope())
						.append("</td><td>").append(jg).append("</td><td>")
						.append(r.getDw() == null ? "" : r.getDw())
						.append("</td></tr>");
			}
		}

		return s.toString();

	}

	public void runImport(InputObj obj) {
		List<String> para = new ArrayList<String>();
		para.add(obj.getUsername());
		boolean idle = dao.ifExist(
				"select * from G_USER where USERNAME=? and COUNT=0", para);
		if (!idle)
			return;
		ImportSkThread thread = new ImportSkThread(obj);

		thread.setQ(obj.getQq());
		thread.deal();
		try {
			dao.update("update G_USER set COUNT=1 where USERNAME=?", para);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String bindsk(String username, String passwd, String logincertCode,
			QueryHttpClient skq) {
		// TODO Auto-generated method stub

		/*
		 * 
		 * // 初始化就登陆 for (int i = 0; i < Const.maxTry; i++) { RJUser user =
		 * skq.logSk(); if (null != user) { if(user.isErrmsg())//仁济的用户名密码输入错误! {
		 * 
		 * throw new Exception(user.getErrMsg());
		 * 
		 * } System.out.println(username + "登陆仁济成功"); // 解析返回字符串，入库
		 * QueryDaoImple dao = new QueryDaoImple(); String sql =
		 * "UPDATE G_USER SET G_USER.`RJUSERNAME`=? ,G_USER.`RJPASSWD`=? WHERE G_USER.`USERNAME`=?"
		 * ; List<String> para = new ArrayList<String>(); para.add(username);
		 * para.add(passwd); para.add(regname); dao.update(sql, para);
		 * 
		 * sql = "insert into RJCARD (CARDNO,USERNAME,CARDTYPE) values(?,?,?)";
		 * String ifexit =
		 * "select * from RJCARD where CARDNO=? and USERNAME=?";// 看看是否存在老卡
		 * List<PhUserCard> ulist = user.getPhUsers().getPhUserCard(); for
		 * (PhUserCard card : ulist) {
		 * 
		 * para.clear();// 添加医保卡 String card_Num = card.getCard_Num();
		 * para.add(card_Num); para.add(regname); if (dao.ifExist(ifexit, para))
		 * continue; para.add("1"); dao.update(sql, para); } return; } }
		 * System.out.println(username + "登陆仁济失败");
		 * 
		 * String
		 * wholeurl="http://yuyue.shdc.org.cn/myFamilyManage.action?title=3";
		 * String back=skq.getHtmlSk(wholeurl);
		 */
		return null;
	}

	public User_SK getSkUser(String username, String passwd) {
		// TODO Auto-generated method stub
		return dao.getSkUser(username, passwd);
	}

	public ChartReport getChartReport(String type) {
		// TODO Auto-generated method stub
		String typestr = Const.ChartReport_1;
		if ("2".equalsIgnoreCase(type))
			typestr = Const.ChartReport_2;
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * FROM DATAS WHERE username='").append(username)
				.append("' AND info in (").append(typestr).append(") ORDER BY reportdate DESC");
		List<Reportdata> datas = dao
				.getAll(sb.toString());
		
		if(null!=datas)
		{
			ChartReport cr=new ChartReport ();
			List<String>timelist=new ArrayList<String>();	
			for(Reportdata r:datas)//把日期单独取出来
			{
				if(!timelist.contains(r.getReportdate()))
					timelist.add(r.getReportdate());
			}
			cr.setTimeLine(timelist);
			cr.setData(datas);
			//用日期一个个索引指标
			return cr;
		}	
		
		return null;
	}
}
